package com.amumu.drama.common.modules.category.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.amumu.drama.common.base.api.CommonPage;
import com.amumu.drama.common.base.api.CommonResult;
import com.amumu.drama.common.constant.ProductTemplateTypeEnum;
import com.amumu.drama.common.dto.GameSkuDTO;
import com.amumu.drama.common.exception.Asserts;
import com.amumu.drama.common.modules.category.dto.GameSkuQueryDto;
import com.amumu.drama.common.modules.category.dto.SkuStockDto;
import com.amumu.drama.common.modules.category.mapping.GameSkuDTO2VoMapping;
import com.amumu.drama.common.modules.category.mapping.PmsSkuStockMapping;
import com.amumu.drama.common.modules.category.mapping.SkuStockDto2PmsSkuStockMapping;
import com.amumu.drama.common.modules.category.service.GameSkuService;
import com.amumu.drama.common.modules.category.service.PmsProductTemplateService;
import com.amumu.drama.common.modules.category.vo.GameSkuVo;
import com.amumu.drama.common.modules.fulu.dto.resp.FuluProductResp;
import com.amumu.drama.common.modules.fulu.service.FuluService;
import com.amumu.drama.mapper.PmsProductTemplateMapper;
import com.amumu.drama.mapper.PmsSkuStockMapper;
import com.amumu.drama.model.PmsProductTemplate;
import com.amumu.drama.model.PmsSkuStock;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @Auther: DM
 * @Date: 2024/6/27 15:18
 * @Description:
 */
@Service
@Log4j2
public class PmsSkuStockServiceImpl extends ServiceImpl<PmsSkuStockMapper, PmsSkuStock> implements GameSkuService {

    @Autowired
    private PmsSkuStockMapper pmsSkuStockMapper;

    @Autowired
    private PmsProductTemplateService productTemplateService;

    @Autowired
    private PmsProductTemplateMapper productTemplateMapper;

    @Autowired
    private FuluService fuluService;

    /**
     * 新增sku
     *
     * @param skuStockDto
     */
    @Override
    public int addSkuStock(SkuStockDto skuStockDto) {
        QueryWrapper<PmsProductTemplate> pmsProductTemplateQueryWrapper = new QueryWrapper<>();
        pmsProductTemplateQueryWrapper.eq("product_category_id", skuStockDto.getProductCategoryId());
        pmsProductTemplateQueryWrapper.eq("delete_status", 0);
        PmsProductTemplate pmsProductTemplate = productTemplateService.getBaseMapper().selectOne(pmsProductTemplateQueryWrapper);
        Asserts.fail(Objects.isNull(pmsProductTemplate), "当前游戏不存在模板,请先创建模板");
        PmsSkuStock pmsSkuStock = SkuStockDto2PmsSkuStockMapping.INSTANCE.convertTo(skuStockDto);
        return pmsSkuStockMapper.insert(pmsSkuStock);
    }

    @Override
    public CommonResult<String> editSkuStock(SkuStockDto skuStockDto) {
        try {
            if (Objects.isNull(skuStockDto.getSkuStockId())) {
                return CommonResult.failed("商品ID不能为空");
            }
            PmsSkuStock pmsSkuStock = pmsSkuStockMapper.selectById(skuStockDto.getSkuStockId());
            if (Objects.isNull(pmsSkuStock)) {
                return CommonResult.failed("商品不存在");
            }
            // 绑定游戏模板
            QueryWrapper<PmsProductTemplate> pmsProductTemplateQueryWrapper = new QueryWrapper<>();
            pmsProductTemplateQueryWrapper.eq("product_category_id", skuStockDto.getProductCategoryId());
            pmsProductTemplateQueryWrapper.eq("delete_status", 0);
            PmsProductTemplate pmsProductTemplate = productTemplateService.getBaseMapper().selectOne(pmsProductTemplateQueryWrapper);
            Asserts.fail(Objects.isNull(pmsProductTemplate), "当前游戏不存在模板,请先创建模板");
            PmsSkuStock savePmsSkuStock = SkuStockDto2PmsSkuStockMapping.INSTANCE.convertTo(skuStockDto);
            savePmsSkuStock.setProductTemplateId(pmsProductTemplate.getId());
            if (pmsSkuStockMapper.updateById(savePmsSkuStock) < 1) {
                return CommonResult.failed("商品修改失败");
            }
            return CommonResult.success();
        } catch (Exception e) {
            log.error("商品修改失败", e);
            return CommonResult.failed("商品修改失败 " + e.getMessage());
        }
    }

    @Override
    public CommonResult<String> deleteSkuStock(Long skuStockId) {
        UpdateWrapper<PmsSkuStock> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", skuStockId).set("delete_status", 1);
        if (!update(updateWrapper)) {
            log.error("商品库存删除失败 skuStockId:{} ", skuStockId);
            return CommonResult.failed("商品库存删除失败");
        }
        return CommonResult.success();
    }

    @Override
    public CommonResult<String> plusOneSkuStock(Long skuStockId) {
        UpdateWrapper<PmsSkuStock> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", skuStockId).setSql("sale = sale+1");
        if (!update(updateWrapper)) {
            log.error("商品销量添加失败 skuStockId:{} ", skuStockId);
            return CommonResult.failed("商品销量添加失败");
        }
        return CommonResult.success();
    }

    @Override
    public CommonPage<GameSkuVo> pageGameSkuList(GameSkuQueryDto gameQueryDto) {
        PageHelper.startPage(gameQueryDto.getPageNum(), gameQueryDto.getPageSize());
        List<GameSkuDTO> gameSkuDTOS = pmsSkuStockMapper.pageGameSkuList(gameQueryDto.getSkuCode(), gameQueryDto.getGameName(), gameQueryDto.getPublishStatus());
        return CommonPage.restPageAndConvert(gameSkuDTOS, GameSkuDTO2VoMapping.INSTANCE::convertTo);
    }

    @Override
    public CommonResult<GameSkuVo> getGameSkuInfo(Long skuStockId) {
        GameSkuVo gameVo = new GameSkuVo();
        PmsSkuStock productTemplate = pmsSkuStockMapper.selectById(skuStockId);
        if (Objects.isNull(productTemplate)) {
            return CommonResult.failed("游戏sku不存在");
        }
        BeanUtil.copyProperties(productTemplate, gameVo);
        return CommonResult.success(gameVo);
    }

    @Override
    public CommonResult<String> batchSynchronizeSkuStock() {
        // 获取所有福禄SKU
        List<FuluProductResp> fuluProductRespList = fuluService.queryProductList();
        log.info("福禄商品同步内容：{}", JSONUtil.toJsonStr(fuluProductRespList));
        List<PmsSkuStock> pmsSkuStocks = PmsSkuStockMapping.INSTANCE.convertTo(fuluProductRespList);
        if (CollectionUtil.isEmpty(pmsSkuStocks)) {
            return CommonResult.success();
        }
        //更新商品模板
        long count = 0L;
        Long oldSkuCount = this.lambdaQuery().eq(PmsSkuStock::getDeleteStatus, 0).count();
        for (PmsSkuStock pmsSkuStock : pmsSkuStocks) {
            if (StrUtil.isNotBlank(pmsSkuStock.getDirectTemplateId())) {
                String productTemplate = fuluService.getProductTemplate(pmsSkuStock.getDirectTemplateId());
                log.info("同步福禄模板信息内容，模板ID：[{}],模板内容：{}", pmsSkuStock.getDirectTemplateId(), productTemplate);
                if (StrUtil.isNotBlank(productTemplate)) {
                    JSONObject jsonObject = JSONUtil.parseObj(productTemplate);
                    PmsProductTemplate pmsProductTemplate = new PmsProductTemplate();
                    pmsProductTemplate.setDirectTemplateId(pmsSkuStock.getDirectTemplateId());
                    pmsProductTemplate.setDirectTemplateField(jsonObject);
                    pmsProductTemplate.setProductCategoryId(pmsSkuStock.getProductCategoryId());
                    pmsProductTemplate.setType(ProductTemplateTypeEnum.DIRECT.getCode());
                    pmsProductTemplate.setDirectChangeStatus(0);
                    LambdaQueryWrapper<PmsProductTemplate> queryWrapper = new LambdaQueryWrapper<PmsProductTemplate>()
                            .eq(PmsProductTemplate::getDirectTemplateId, pmsSkuStock.getDirectTemplateId())
                            .eq(PmsProductTemplate::getDeleteStatus, 0)
                            .eq(PmsProductTemplate::getType, ProductTemplateTypeEnum.DIRECT.getCode());
                    PmsProductTemplate template = productTemplateMapper.selectOne(queryWrapper);
                    if (template == null) {
                        pmsProductTemplate.setTemplateName(jsonObject.getStr("addressName"));
                        pmsProductTemplate.setCustomTemplateField(pmsProductTemplate.getDirectTemplateField());
                        productTemplateMapper.insert(pmsProductTemplate);
                    } else {
                        pmsProductTemplate.setId(template.getId());
                        if (StrUtil.isBlank(template.getTemplateName())) {
                            pmsProductTemplate.setTemplateName(jsonObject.getStr("addressName"));
                        }
                        if (!jsonObject.equals(template.getDirectTemplateField())) {
                            pmsProductTemplate.setDirectChangeStatus(1);
                        }
                        productTemplateMapper.updateById(pmsProductTemplate);
                    }
                    pmsSkuStock.setProductTemplateId(pmsProductTemplate.getId());
                }
            }
            if (this.saveOrUpdate(pmsSkuStock, new LambdaUpdateWrapper<PmsSkuStock>()
                    .eq(PmsSkuStock::getSkuCode, pmsSkuStock.getSkuCode()))) {
                count++;
            }
        }
        Long newSkuCount = this.lambdaQuery().eq(PmsSkuStock::getDeleteStatus, 0).count();
        if (pmsSkuStocks.size() != count) {
            String msg = StrUtil.format("游戏sku同步成功失败：数据共[{}],失败[{}],原[{}]，现[{}]", pmsSkuStocks.size(), (pmsSkuStocks.size() - count), oldSkuCount, newSkuCount);
            log.error(msg);
            return CommonResult.failed(msg);
        }
        String msg = StrUtil.format("游戏sku同步成功[{}]条，原[{}]条，现[{}]条", count, oldSkuCount, newSkuCount);
        log.info(msg);
        return CommonResult.success(msg);
    }

}
